package com.hz.activity7.level;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Random;

@RestController
@RequestMapping("/te")
public class ActivitiController {

    @Autowired
    private ImageServiceImpl imageService;

    /**
     * 根据流程定义id查看流程图
     * @return
     */
    @PostMapping("/image")
    //@ApiOperation(value = "根据流程定义id查看流程图", notes = "根据流程定义id，查询返回不带节点流转信息的图片")
    public void image(@RequestBody JSONObject jsonObject, HttpServletResponse response) {
        try (OutputStream out = response.getOutputStream();
             InputStream is = imageService.getFlowImgByProcInstId(jsonObject.getString("id"), null, false)) {
            if (null != is) {
                BufferedImage image = ImageIO.read(is);

                response.setContentType("image/png");
                ImageIO.write(image, "png", out);
            }
        } catch (Exception ex) {
            System.err.println("查看流程图失败: "+ ex);
        }
    }


    public void saveImageToLocal(@RequestBody JSONObject jsonObject) {
        String procInstId = jsonObject.getString("id");
        if (procInstId == null || procInstId.isEmpty()) {
            System.err.println("Process instance ID is missing.");
            return;
        }

        InputStream is = null;
        try {
            // 获取流程图输入流
            is = imageService.getFlowImgByProcInstId(null, procInstId, true);
            if (is == null) {
                System.err.println("Process image not found for ID: " + procInstId);
                return;
            }

            BufferedImage image = ImageIO.read(is);
            if (image == null) {
                System.err.println("Failed to read image data for process ID: " + procInstId);
                return;
            }

            // 设置保存路径和文件名
            File outputFile = new File("D:\\javaXM\\activity7\\src\\main\\resources\\" +  new Random().nextInt(100) + ".png");
            // 确保目录存在
            outputFile.getParentFile().mkdirs();

            // 写入图像到本地文件
            ImageIO.write(image, "png", outputFile);

            System.out.println("Image saved successfully at: " + outputFile.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("Error saving image locally: " + e.getMessage());
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}


